package mspdt.ontrade;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.Engine;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.modifier.DelayModifier;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.modifier.ParallelEntityModifier;
import org.andengine.entity.modifier.RotationByModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.scene.background.SpriteBackground;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.ITextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.opengl.texture.render.RenderTexture;
import org.andengine.opengl.util.GLState;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.BaseGameActivity;
import org.andengine.ui.activity.LayoutGameActivity;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.IModifier;
import org.andengine.util.modifier.ease.EaseBackInOut;
import org.andengine.util.modifier.ease.EaseCircularOut;
import org.andengine.util.modifier.ease.EaseQuadInOut;
import org.andengine.util.modifier.ease.EaseQuadOut;
import org.andengine.util.modifier.ease.EaseSineInOut;
import org.andengine.util.modifier.ease.EaseSineOut;
import org.andengine.util.modifier.ease.EaseStrongOut;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.opengl.GLES20;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Game2Activity extends LayoutGameActivity implements IOnMenuItemClickListener, IOnSceneTouchListener{

	private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 720;
	private Camera mCamera;
	private Scene mainScene;
	private Sprite change, info;
	private BitmapTextureAtlas cardTexttureAtlas, flipCardsTextureAtlas, flipped1CardsAtlas, flipped2CardsAtlas, flipped3CardsAtlas, flipped4CardsAtlas
	, flipped5CardsAtlas, flipped6CardsAtlas, flipped7CardsAtlas, devilTextureAtlas;
    private ITextureRegion cardTextureRegion, flipCardsTexttureRegion, devilTextureRegion, 
    	flippedCard1TextureRegion, flippedCard2TextureRegion, flippedCard3TextureRegion, flippedCard4TextureRegion, flippedCard5TextureRegion, 
    	flippedCard6TextureRegion, flippedCard7TextureRegion, current_region;
    private boolean mMotionStreaking = false, isFlipped = false, isMod = true;
    ArrayList<Sprite> cards = new ArrayList<Sprite>(), flipped_cards = new ArrayList<Sprite>();
    int player_number = 0;
    Sprite back;
    private Sound shuffle, click, laught;
	float rotationCenterX = 0f;
	float rotationCenterY = 0f;
    EditText players;
    Button done;
    LinearLayout ll;
    int limitReached = 0;
	int devil = 0;
	@Override
	public EngineOptions onCreateEngineOptions() {
		// TODO Auto-generated method stub
		mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		
		EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), mCamera);
		engineOptions.getTouchOptions().setNeedsMultiTouch(true);
		mCamera.setZClippingPlanes(-100, 100);
		engineOptions.getAudioOptions().setNeedsSound(true);
		return engineOptions;
	}	
	@Override
	public void onCreateResources(
			OnCreateResourcesCallback pOnCreateResourcesCallback)
			throws Exception {
		// TODO Auto-generated method stub
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("pic/");
		cardTexttureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		flipped1CardsAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		flipped2CardsAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		flipped3CardsAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		flipped4CardsAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		flipped5CardsAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		flipped6CardsAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		flipped7CardsAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		
		devilTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 240, 360, TextureOptions.DEFAULT);
		cardTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(cardTexttureAtlas, this, "card_backside.png", 0, 0);
		flippedCard1TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(flipped1CardsAtlas, this, "card1.png", 0, 0);
		flippedCard2TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(flipped2CardsAtlas, this, "card2.png", 0, 0);
		flippedCard3TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(flipped3CardsAtlas, this, "card3.png", 0, 0);
		flippedCard4TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(flipped4CardsAtlas, this, "card4.png", 0, 0);
		flippedCard5TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(flipped5CardsAtlas, this, "card5.png", 0, 0);
		flippedCard6TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(flipped6CardsAtlas, this, "card6.png", 0, 0);
		flippedCard7TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(flipped7CardsAtlas, this, "card7.png", 0, 0);
		devilTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(devilTextureAtlas, this, "joker.png", 0, 0);
		cardTexttureAtlas.load();
		flipped1CardsAtlas.load();
		flipped2CardsAtlas.load();
		flipped3CardsAtlas.load();
		flipped4CardsAtlas.load();
		flipped5CardsAtlas.load();
		flipped6CardsAtlas.load();
		flipped7CardsAtlas.load();
		
		devilTextureAtlas.load();
		
		BitmapTextureAtlas changeTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 150, 50, TextureOptions.DEFAULT);
		ITextureRegion changeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(changeTextureAtlas, this, "game2_change.png", 0, 0);
		changeTextureAtlas.load();
		float change_w = 99f;
		float change_h = 33f;
		change = new Sprite(55, CAMERA_HEIGHT-change_h-10, change_w, change_h, changeTextureRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if(TouchEvent.ACTION_DOWN == pSceneTouchEvent.getAction())
				{
					this.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.15f, 1.0f, 1.1f), new ScaleModifier(0.15f, 1.1f, 1.0f)));
				}
				else if(TouchEvent.ACTION_UP == pSceneTouchEvent.getAction())
				{
					this.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
						@Override
						public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
							Game2Activity.this.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									
								}
							});
						}

						@Override
						public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
							Game2Activity.this.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									//mEngine.stop();
									//Game2Activity.this.finish();
									Game2Activity.this.ll.setVisibility(View.VISIBLE);
								}
							});
						}
					}, new SequenceEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.15f, 1.0f, 1.1f), new ScaleModifier(0.15f, 1.1f, 1.0f)))));
				}
				return true;
			}
		};
		
		flipCardsTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 171, 171, TextureOptions.DEFAULT);
		flipCardsTexttureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(flipCardsTextureAtlas, this, "flipcards.png", 0, 0);
		flipCardsTextureAtlas.load();
    	
		SoundFactory.setAssetBasePath("mfx/");
		try {
			this.shuffle = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "game2_shuffle1.mp3");
			this.click = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "click.mp3");
			this.laught = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "laught.mp3");
		} catch (final IOException e) {
			Debug.e(e);
		}
		
		pOnCreateResourcesCallback.onCreateResourcesFinished();
	}

	@Override
	public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
			throws Exception {
		// TODO Auto-generated method stub
		mainScene = new Scene();
		
		BitmapTextureAtlas bgTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 768, 1024, TextureOptions.DEFAULT);
		ITextureRegion bgTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bgTextureAtlas, this, "game2_back.jpg", 0, 0);
		bgTextureAtlas.load();
		Sprite bgSprite = new Sprite(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, bgTextureRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				//if(devil!=Integer.parseInt(this.getUserData().toString()))
					//this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
				//male.clearEntityModifiers();
				return true;
			}
		};
		SpriteBackground bg = new SpriteBackground(bgSprite);
		
		
		mainScene.setBackground(bg);
		this.mainScene.setOnAreaTouchTraversalFrontToBack();


		this.mainScene.setTouchAreaBindingOnActionDownEnabled(true);
		
		BitmapTextureAtlas backTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 127, 127, TextureOptions.DEFAULT);
		ITextureRegion backTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(backTextureAtlas, this, "back.png", 0, 0);
		backTextureAtlas.load();
		back = new Sprite(20, -10, 80, 80, backTextureRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
					if(TouchEvent.ACTION_UP == pSceneTouchEvent.getAction())
					{
						this.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
							@Override
							public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
								Game2Activity.this.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										click.play();
									}
								});
							}

							@Override
							public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
								Game2Activity.this.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										mainScene.clearTouchAreas();
										mainScene.detachChildren();
										mainScene.clearUpdateHandlers();
										mEngine.stop();
										Game2Activity.this.finish();
									}
								});
							}
						}, new SequenceEntityModifier(new MoveModifier(0.6f, back.getX(), back.getX(), back.getY(), back.getY()-back.getHeight(), EaseBackInOut.getInstance()), new DelayModifier(0))));
					}
				return true;
			}
		};
		BitmapTextureAtlas infoAtlas = new BitmapTextureAtlas(this.getTextureManager(), 39, 39, TextureOptions.DEFAULT);
		ITextureRegion infoRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(infoAtlas, this, "help.png", 0, 0);
		infoAtlas.load();
		info = new Sprite(430, 670, 40, 40, infoRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if(pSceneTouchEvent.isActionUp())
				{
					final AlertDialog.Builder alert = new AlertDialog.Builder(Game2Activity.this);
					alert.setTitle(getResources().getString(R.string.info_title));
					alert.setMessage(getResources().getString(R.string.game2_info));
					//alert.show();
					Game2Activity.this.runOnUiThread(new Runnable() {
					    @Override
					    public void run() {
					    	alert.show();
//					    	Game1Activity.this.showDialog(MY_DIALOG_ID);
					    }
					});
				}
				return true;
			}
		};
		mainScene.attachChild(back);
		mainScene.registerTouchArea(back);
		mainScene.attachChild(info);
		mainScene.registerTouchArea(info);
		
		
		pOnCreateSceneCallback.onCreateSceneFinished(this.mainScene);
	}
	@Override
	public void onBackPressed()
	{
		back.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
			@Override
			public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
				Game2Activity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						click.play();
					}
				});
			}
			@Override
			public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
				Game2Activity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mainScene.clearTouchAreas();
						mainScene.detachChildren();
						mainScene.clearUpdateHandlers();
						mEngine.stop();
						Game2Activity.this.finish();
					}
				});
			}
		}, new SequenceEntityModifier(new MoveModifier(0.6f, back.getX(), back.getX(), back.getY(), back.getY()-back.getHeight(), EaseBackInOut.getInstance()), new DelayModifier(0))));
	}
	@Override
	public void onPopulateScene(Scene pScene,
			OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
		// TODO Auto-generated method stub
		pOnPopulateSceneCallback.onPopulateSceneFinished();
	}

	
	@Override
	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {
			return false;

		
	}


	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub
		//rotateBottle();
		return true;
	}

	@Override
	protected int getLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.gam2_layout;
	}

	@Override
	protected int getRenderSurfaceViewID() {
		// TODO Auto-generated method stub
		return R.id.game2_surface;
	}
	@Override
	protected void onSetContentView() {
		super.onSetContentView();
		this.players = (EditText)this.findViewById(R.id.enter_player);
		this.done = (Button)this.findViewById(R.id.start_game);
		this.done.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(players.getText().toString().length() > 0)
				{
					if(players.getText().toString().contains("(") || players.getText().toString().contains(")") || players.getText().toString().contains("/") ||
							 players.getText().toString().contains("-") || players.getText().toString().contains("+") || players.getText().toString().contains("#") ||
							 players.getText().toString().contains(".") || players.getText().toString().contains(",") || players.getText().toString().contains(";") || 
							 players.getText().toString().contains("*") || players.getText().toString().contains("N"))
					{
						AlertDialog.Builder alert = new AlertDialog.Builder(Game2Activity.this);
						alert.setTitle(getResources().getString(R.string.game2_error_title));
						alert.setMessage(getResources().getString(R.string.game2_error_nonint));
						alert.show();
					}
					else
					{
						InputMethodManager imm = (InputMethodManager)getSystemService(
							      Game2Activity.this.INPUT_METHOD_SERVICE);
							imm.hideSoftInputFromWindow(players.getWindowToken(), 0);
						player_number = Integer.parseInt(players.getText().toString());
						restartGame();
						
						ll.setVisibility(View.GONE);
						mainScene.registerTouchArea(back);
						mainScene.registerTouchArea(change);
						isFlipped = false;
					}
					
				}
				else
				{
					AlertDialog.Builder alert = new AlertDialog.Builder(Game2Activity.this);
					alert.setTitle(getResources().getString(R.string.game2_error_title));
					alert.setMessage(getResources().getString(R.string.game2_error_body));
					alert.show();
				}
				
				//mainScene.setOnSceneTouchListener(Game2Activity.this);
			}
		});
		this.ll = (LinearLayout)this.findViewById(R.id.game2_ll);
	}
	
	public void restartGame()
	{
		shuffle.play();
		mainScene.detachChildren();
		mainScene.attachChild(back);
		mainScene.attachChild(change);
		mainScene.attachChild(info);
		cards.clear();
		Random rand = new Random();
		devil = rand.nextInt(player_number);
		for(int i=0;i<player_number;i++)
		{
			Sprite card = new Sprite(0, 0, 60, 90, cardTextureRegion, mEngine.getVertexBufferObjectManager())
			{
				@Override
				public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
					//if(devil!=Integer.parseInt(this.getUserData().toString()))
						this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
					return true;
				}
				@Override
				protected void applyRotation(final GLState pGLState) {
					final float rotation = this.mRotation;

					if(rotation != 0) {
						final float rotationCenterX = this.mRotationCenterX;
						final float rotationCenterY = this.mRotationCenterY;

						pGLState.translateModelViewGLMatrixf(rotationCenterX, rotationCenterY, 0);
						/* Note we are applying rotation around the y-axis and not the z-axis anymore! */
						pGLState.rotateModelViewGLMatrixf(rotation, 0, 1, 0);
						pGLState.translateModelViewGLMatrixf(-rotationCenterX, -rotationCenterY, 0);
					}
				}
			};
			card.setUserData(i);
			
	    	
	    	float radius = 150;
	    	card.setPosition(CAMERA_WIDTH/2-card.getWidth()/2, CAMERA_HEIGHT/2-card.getHeight()/2);
	    	//card.setRotation((i+1)*(360/player_number));
	    	float angle = 90+(i+1)*(360/player_number);
	    	float fromX = card.getX();
	    	float fromY = card.getY();
	    	//card.set
	    	float toX = (float)(radius*Math.cos(angle*(Math.PI/180)))+fromX;
	    	float toY = (float)(radius*Math.sin(angle*(Math.PI/180)))+fromY;
	    	card.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
				@Override
				public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
					Game2Activity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							//Toast.makeText(Game1Activity.this, "Sequence started.", Toast.LENGTH_SHORT).show();
						}
					});
				}

				@Override
				public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
					Game2Activity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							isMod=false;
						}
					});
				}
			}, new MoveModifier(0.3f, fromX, toX, fromY, toY)));
	    	cards.add(card);
			mainScene.attachChild(card);
			mainScene.registerTouchArea(card);
		}
		Sprite flipCardsSprite = new Sprite(0, 0, 75, 75, flipCardsTexttureRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				//if(devil!=Integer.parseInt(this.getUserData().toString()))
				if(TouchEvent.ACTION_UP == pSceneTouchEvent.getAction())
				{
					if(!isMod)
					{
						isMod = true;
						if(!isFlipped)
						{
							this.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.15f, 1f, 1.3f), new ScaleModifier(0.15f, 1.3f, 1f)));
							flipCards();
							isFlipped = true;
						}
						else
						{
							restartGame();
							isFlipped = false;
						}
					}
					
				}
				
					
					//this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
				return true;
			}
			
		};
		flipCardsSprite.setPosition(CAMERA_WIDTH/2-flipCardsSprite.getWidth()/2, CAMERA_HEIGHT/2-flipCardsSprite.getHeight()/2);
		mainScene.attachChild(flipCardsSprite);
		mainScene.registerTouchArea(flipCardsSprite);
		flipCardsSprite.registerEntityModifier(new ScaleModifier(0.5f, 0f, 1f));
	}
	public void flipCards()
	{
		flipped_cards.clear();
		limitReached = 0;
		for(int i=0;i<player_number;i++)
		{
			current_region = null;
			if(devil == Integer.parseInt(cards.get(i).getUserData().toString()))
				current_region = devilTextureRegion;
			else
			{
				Random rand = new Random();
				int which = rand.nextInt(7);
				Log.d("TEST", "which="+which);
				switch(which)
				{
				case 0: current_region = flippedCard1TextureRegion; break;
				case 1: current_region = flippedCard2TextureRegion; break;
				case 2: current_region = flippedCard3TextureRegion; break;
				case 3: current_region = flippedCard4TextureRegion; break;
				case 4: current_region = flippedCard5TextureRegion; break;
				case 5: current_region = flippedCard6TextureRegion; break;
				default: current_region = flippedCard7TextureRegion; break;
				}
			}
				
			Sprite flipped = new Sprite(cards.get(i).getX(), cards.get(i).getY(), current_region, cards.get(i).getVertexBufferObjectManager()) {
				@Override
				protected void applyRotation(final GLState pGLState) {
					final float rotation = this.mRotation;

					if(rotation != 0) {
						rotationCenterX = this.mRotationCenterX;
						rotationCenterY = this.mRotationCenterY;
						//mainRotationX = rotationCenterX+cards.get(0).getWidth()/2;

						pGLState.translateModelViewGLMatrixf(rotationCenterX, rotationCenterY, 0);
						/* Note we are applying rotation around the y-axis and not the z-axis anymore! */
						pGLState.rotateModelViewGLMatrixf(rotation, 0, 1, 0);
						pGLState.translateModelViewGLMatrixf(-rotationCenterX, -rotationCenterY, 0);
					}
				}
				
			};
			flipped.setHeight(cards.get(i).getHeight());
			flipped.setWidth(cards.get(i).getWidth());
			flipped.setRotationCenter(cards.get(i).getRotationCenterX(), rotationCenterY);
			flipped.setUserData(i);
			flipped.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
				@Override
				public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
					Game2Activity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							//Toast.makeText(Game1Activity.this, "Sequence started.", Toast.LENGTH_SHORT).show();
						}
					});
				}

				@Override
				public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
					Game2Activity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							if(Integer.parseInt(pEntity.getUserData().toString()) == devil)
							{
								laught.play();
								pEntity.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.3f, 1.0f, 1.2f), new ScaleModifier(0.3f, 1.2f, 1.0f)), 2));
							}
								
							isMod = false;
						}
					});
				}
			}, new RotationModifier(0.5f, 270, 360)));
			flipped_cards.add(flipped);
			cards.get(i).registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
				@Override
				public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
					Game2Activity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							//Toast.makeText(Game1Activity.this, "Sequence started.", Toast.LENGTH_SHORT).show();
						}
					});
				}

				@Override
				public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
					Game2Activity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							limitReached++;
							if(limitReached == player_number)
							{
								detachCards();
								attachCards();
							}
								
							//mainScene.attachChild(flipped);
						}
					});
				}
			}, new RotationModifier(0.5f, 0f, 90f)));			
		}
	}
	public void attachCards()
	{
		for(int i=0;i<flipped_cards.size();i++)
		{
			mainScene.attachChild(flipped_cards.get(i));
//			if(Integer.parseInt(flipped_cards.get(i).getUserData().toString())==devil)
//			{
//				flipped_cards.get(i).registerEntityModifier(new ScaleModifier(0.2f, 1f, 1.2f));
//			}
		}
	}
	public void detachCards()
	{
		for(int i = 0; i<player_number;i++)
		{
			mainScene.detachChild(cards.get(i));
		}
	}

}
